package com.haike.pushjobs.config;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class QuartzJobDataSourceAspect {

    /**
     * 切点：拦截所有Quartz Job的execute方法
     */
    @Pointcut("execution(* org.quartz.Job+.execute(..))")
    public void quartzJobPointcut() {
    }

    /**
     * 执行前设置数据源上下文
     */
    @Before("quartzJobPointcut()")
    public void quartzJobBefore() {
        log.info("当前Job执行前数据源(null就是yml中dynamic.primary): {}", DynamicDataSourceContextHolder.peek());
    }

    /**
     * 执行后清除数据源上下文
     */
    @After("quartzJobPointcut()")
    public void clearDataSourceContext() {
        log.info("当前Job执行后: 清除当前线程数据源上下文, 防止线程被复用时, 数据源互窜");
        DynamicDataSourceContextHolder.clear();
    }
}